(:
  A procedure to find threading information finding the first ancestor given 
  parentid and id facetnames 
:)
declare boundary-space strip;
import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;
declare variable $doc := doc($arguments[1]);
declare variable $items := $doc/display/item;
declare variable $idfacet := jj:get-one($arguments[2],"messageid");
declare variable $parentidfacet := jj:get-one($arguments[3],"parentid");
declare variable $condfacet := jj:get-one($arguments[4],"type");
declare variable $condvalue := jj:get-one($arguments[5],"add message");
declare function local:find-ancestor-id ($item as item()) as xs:string 
		{
			let $id := xs:string(jj:get-info($item,$idfacet))
			return
			if (jj:get-info($item,$parentidfacet)) then
				let $parentid := jj:get-info($item,$parentidfacet)
				let $ancestor := $items[xs:string(jj:get-info(.,$condfacet)) = $condvalue][xs:string(jj:get-info(.,$idfacet)) = $parentid][1]
				return
				if ($ancestor) then
				  local:find-ancestor-id($ancestor)
				else
					$id (: ancestor was not of correct type :)
			else
				$id (: no ancestor at all :)
		};
 
<display>{
for $item in $items
return
<item>{
		for $info in $item/info return $info,
		if (xs:string(jj:get-info($item,$condfacet)) = $condvalue) then
		  <info name="thread">{local:find-ancestor-id($item)}</info>
		else
			()  
  }</item>
}</display>
